package com.jinxi.algorithm.leetcode;

/**
 * @Autho changqi.wu
 * @Date 路在脚下，使劲踩！
 */
public class MixCode2 {

    public static void main(String[] args) {
        MixCode2 m = new MixCode2();
        int[] barss = {1, 1, 1, 1, 2, 2, 3, 3};
        print(m.rearrangeBarcodes(barss));


//        int[] bars = {1, 3, 2, 3, 1, 2, 1};
//        int val = 1;
//        int[] result = m.compare(bars, val);
//        print(result);
    }

    public static void print(int[] bar) {
        for (int i : bar) {
            System.out.print(i + "\t");
        }
        System.out.println();
    }

    public int[] rearrangeBarcodes(int[] barcodes) {
        int size = barcodes.length;
        int[] target = new int[size];
        int[] unuse = new int[size];
        int index = 0;
        for (int i = 0; i < size - 1; i++) {
            if (barcodes[i] == barcodes[i + 1]) { //塞到队列尾部
                unuse[i - index] = barcodes[i];
                continue;
            } else {
                target[index++] = barcodes[i];
            }
        }

        unuse[size - 1 - index] = barcodes[size - 1];

        int[] bars = new int[index];
        for (int i = 0; i < index; i++) {
            bars[i] = target[i];
        }

        int s = size - index;
        for (int i = 0; i < s; i++) {
            bars = compare(bars, unuse[i]);
        }

        return bars;
    }


    /**
     * 倒序
     *
     * @param bars
     * @param val
     * @return
     */
    public int[] compare(int[] bars, int val) {
        int[] target = new int[bars.length + 1];
        boolean flag = false;
        for (int i = bars.length - 1; i > 0; i--) {
            int temp1 = bars[i];
            int temp2 = bars[i - 1];
            if (flag) {
                target[i] = bars[i];
            } else {
                target[i + 1] = bars[i];

                if (temp1 != val && temp2 != val) {
                    target[i] = val;
                    flag = true;
                }
            }

        }
        if (flag) {
            target[0] = bars[0];
        } else {
            target[1] = bars[0];
            target[0] = val;
        }
        return target;
    }
}
